#include "vars.h"
#include "actions.h"
#include "ui.h"
#include "screens.h"
#include <esp_log.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "boards/startnorva/sd_card.h"
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_host.h"

#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <vector>
#include <algorithm>

#include "src/misc/lv_timer.h"
#include "application.h"

#include "esp_system.h" 
#include "esp_timer.h"
#include "esp_random.h" 


static const char* TAG = "ui_ball";

LV_FONT_DECLARE(font_puhui_20_4);

// 屏幕与游戏参数定义
#define SCREEN_WIDTH 280
#define SCREEN_HEIGHT 240
#define BIRD_SIZE 20
#define PIPE_WIDTH 40
#define PIPE_GAP 80       // 管道上下间隙
#define PIPE_SPEED 2      // 管道移动速度
#define GRAVITY 1         // 重力加速度
#define JUMP_FORCE 20     // 跳跃力度
#define GROUND_HEIGHT 20  // 地面高度
#define GROUND_Y (SCREEN_HEIGHT - GROUND_HEIGHT)  // 地面Y坐标（底部）
#define MIN_PIPE_SPACING 100  // 管道最小间距（修复重叠的关键参数）
#define MAX_PIPE_SPACING 250  // 管道最大间距

// 全局变量
static lv_obj_t *bird;                  // 小鸟对象
static lv_obj_t *pipes[10];             // 上管对象数组
static lv_obj_t *bottom_pipes[10];      // 下管对象数组
static lv_obj_t *ground;                // 地面对象
static lv_obj_t *score_label;           // 分数标签
static lv_timer_t *game_timer;          // 游戏定时器
static int bird_y = SCREEN_HEIGHT / 2;  // 小鸟Y坐标
static int pipe_x[10];                  // 管道X坐标数组
static int pipe_top_height[10];         // 上管高度数组
static int score = 0;                   // 分数
static bool game_started = false;       // 游戏状态（是否开始）
static lv_obj_t *game_over_score_label = nullptr; //用于存储游戏结束时显示得分的标签

// 重置随机数种子
static void reset_random_seed() {
    uint32_t seed = esp_timer_get_time();
    srand(seed);
    ESP_LOGI(TAG, "随机数种子已重置: %" PRIu32, seed);
}

// 小鸟跳跃函数
static void bird_jump() {
    if (game_started) {
        ESP_LOGI(TAG, "JUMP_FORCE 当前值: %d", JUMP_FORCE);
        bird_y -= JUMP_FORCE;
        if (bird_y < 0) bird_y = 0;  // 限制不超出屏幕顶部
        lv_obj_set_y(bird, bird_y);
        vTaskDelay(pdMS_TO_TICKS(10)); 
    }
}

// 触摸事件处理
static void touch_event_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_PRESSED) {
        bird_jump();
        vTaskDelay(pdMS_TO_TICKS(10)); 
        ESP_LOGI(TAG, "触摸事件触发跳跃");
    }
}

// 重置游戏
static void reset_game() {
    // 停止并删除定时器
    if (game_timer) {
        lv_timer_del(game_timer);
        game_timer = NULL;
    }
     ESP_LOGI(TAG, "停止并删除定时器");
    
    // 彻底销毁旧的小鸟对象
    if (bird) {
        lv_obj_del(bird);
        bird = NULL;
    }
    ESP_LOGI(TAG, "彻底销毁旧的小鸟对象");
    
    // 重置小鸟位置
    bird_y = SCREEN_HEIGHT / 2;
    ESP_LOGI(TAG, "重置小鸟位置");
    
    // 重置分数
    score = 0;
    // if (score_label) lv_label_set_text(score_label, "0");
    // ESP_LOGI(TAG, "重置分数");

        if (score_label) {
        lv_obj_del(score_label);  // 销毁标签对象
        score_label = NULL;       // 重置指针为NULL
    }
    
    // 清除所有管道
    for (int i = 0; i < 10; i++) {
        if (pipes[i]) {
            lv_obj_del(pipes[i]);
            pipes[i] = NULL;
        }
        if (bottom_pipes[i]) {
            lv_obj_del(bottom_pipes[i]);
            bottom_pipes[i] = NULL;
        }
    }
    ESP_LOGI(TAG, "清除所有管道");


        // 销毁地面对象
    if (ground) {
        lv_obj_del(ground);
        ground = nullptr;
    }
      ESP_LOGI(TAG, "销毁地面对象");
    
    
    // 隐藏游戏开始按钮
    if (objects.ball_start) {
        lv_obj_add_flag(objects.ball_start, LV_OBJ_FLAG_HIDDEN);
        
    }
      ESP_LOGI(TAG, "隐藏游戏开始按钮");


    // 移除屏幕的触摸事件回调
    lv_obj_remove_event_cb(lv_scr_act(), touch_event_handler);
          ESP_LOGI(TAG, "移除屏幕的触摸事件回调");
    
    game_started = false;
    reset_random_seed();
}



// 游戏失败处理
static void game_over() {
    game_started = false;
    // 显示开始按钮
    if (objects.ball_start) {
        lv_obj_clear_flag(objects.ball_start, LV_OBJ_FLAG_HIDDEN);
    }
    ESP_LOGI(TAG, "游戏结束，可点击开始按钮重启");

}

static void game_over_label() {

    // 创建或更新游戏结束得分标签
    if (!game_over_score_label) {
        game_over_score_label = lv_label_create(lv_scr_act());
    }

    // 构建显示文本
    std::string score_text = "最终得分: " + std::to_string(score);
    lv_label_set_text(game_over_score_label, score_text.c_str());

    // 使用 lv_obj_align 函数将标签居中
    lv_obj_align(game_over_score_label, LV_ALIGN_CENTER, 0, -50);

    // 设置标签样式
    lv_obj_set_style_text_color(game_over_score_label, lv_color_black(), 0);
    lv_obj_set_style_text_font(game_over_score_label, &font_puhui_20_4, 0);
    lv_obj_move_foreground(game_over_score_label);
}



// 管道与小鸟碰撞检测及游戏逻辑
static void game_timer_cb(lv_timer_t *timer) {
    if (!game_started) return;

    // 小鸟受重力下落
    bird_y += GRAVITY;
    if (bird_y + BIRD_SIZE > GROUND_Y) {
        bird_y = GROUND_Y - BIRD_SIZE;
    }
    lv_obj_set_y(bird, bird_y);

    // 检测触地（游戏失败）
    if (bird_y + BIRD_SIZE >= GROUND_Y) {
        ESP_LOGE(TAG, "触地失败！分数: %d", score);
        game_over_label();
        reset_game();
        game_over();
        
        return;
    }

    // 管道移动与碰撞检测
    for (int i = 0; i < 10; i++) {
        if (pipes[i] && bottom_pipes[i]) {
            // 移动管道（向左）
            pipe_x[i] -= PIPE_SPEED;
            lv_obj_set_x(pipes[i], pipe_x[i]);
            lv_obj_set_x(bottom_pipes[i], pipe_x[i]);

            // 穿过管道计分
            if (pipe_x[i] + PIPE_WIDTH < lv_obj_get_x(bird) && 
                pipe_x[i] + PIPE_WIDTH + PIPE_SPEED >= lv_obj_get_x(bird)) {
                score++;
                std::string score_str = std::to_string(score);
                lv_label_set_text(score_label, score_str.c_str());
                // 将分数标签移到最前面
                lv_obj_move_foreground(score_label);
                ESP_LOGI(TAG, "得分！当前分数: %d", score);
            }


            // 碰撞检测坐标计算
            int birdLeft = lv_obj_get_x(bird);
            int birdRight = birdLeft + BIRD_SIZE;
            int birdTop = lv_obj_get_y(bird);
            int birdBottom = birdTop + BIRD_SIZE;
            int pipeLeft = pipe_x[i];
            int pipeRight = pipeLeft + PIPE_WIDTH;
            int pipeTopBottom = pipe_top_height[i];
            int pipeBottomTop = pipe_top_height[i] + PIPE_GAP;

            // 检测与上管碰撞
            if (birdRight > pipeLeft && birdLeft < pipeRight && birdTop < pipeTopBottom) {
                ESP_LOGE(TAG, "撞上管失败！分数: %d", score);
                game_over_label();
                reset_game();
                game_over();
               
                return;
            }

            // 检测与下管碰撞
            if (birdRight > pipeLeft && birdLeft < pipeRight && birdBottom > pipeBottomTop) {
                ESP_LOGE(TAG, "撞下管失败！分数: %d", score);
                game_over_label();
                reset_game();
                game_over();
                
                return;
            }

            // 管道完全移出左侧屏幕后重新生成（核心修复部分）
            if (pipe_x[i] + PIPE_WIDTH < 0) {
                lv_obj_del(pipes[i]);
                lv_obj_del(bottom_pipes[i]);

                // 计算前一个管道索引（循环取模避免越界）
                int prev_idx = (i == 0) ? 9 : i - 1;
                
                // 确保前一个管道存在且有效
                int base_x = (pipes[prev_idx] && bottom_pipes[prev_idx]) 
                            ? (pipe_x[prev_idx] + PIPE_WIDTH)  // 基于前一个管道的右侧位置计算
                            : SCREEN_WIDTH;  // 初始管道从屏幕右侧开始
                
                // 生成随机间距（在最小和最大间距之间）
                int random_gap = MIN_PIPE_SPACING + (rand() % (MAX_PIPE_SPACING - MIN_PIPE_SPACING + 1));
                pipe_x[i] = base_x + random_gap;
                
                // 记录管道生成信息（调试用）
                ESP_LOGI(TAG, "生成管道 %d: 前管道X=%d, 间距=%d, 新X=%d", 
                         i, base_x, random_gap, pipe_x[i]);
               
                // 上管高度限制（增加随机性范围）
                int max_top = SCREEN_HEIGHT - PIPE_GAP - GROUND_HEIGHT - 50;
                if (max_top < 30) max_top = 30;
                pipe_top_height[i] = 30 + (rand() % (max_top - 30));  // 30到max_top之间的随机高度

                // 创建上管
                pipes[i] = lv_obj_create(lv_scr_act());
                lv_obj_set_size(pipes[i], PIPE_WIDTH, pipe_top_height[i]);
                lv_obj_set_pos(pipes[i], pipe_x[i], 0);
                lv_obj_set_style_bg_color(pipes[i], lv_palette_main(LV_PALETTE_GREEN), 0);

                // 创建下管
                int bottom_pipe_y = pipe_top_height[i] + PIPE_GAP;
                int bottom_pipe_h = GROUND_Y - bottom_pipe_y;
                if (bottom_pipe_h < 30) bottom_pipe_h = 30;
                bottom_pipes[i] = lv_obj_create(lv_scr_act());
                lv_obj_set_size(bottom_pipes[i], PIPE_WIDTH, bottom_pipe_h);
                lv_obj_set_pos(bottom_pipes[i], pipe_x[i], bottom_pipe_y);
                lv_obj_set_style_bg_color(bottom_pipes[i], lv_palette_main(LV_PALETTE_GREEN), 0);
            }
        }
    }
}

// 初始化游戏场景
static void init_game_scene() {


    // 创建并设置背景样式
    static lv_style_t style_bg;
    lv_style_init(&style_bg);
    lv_style_set_bg_color(&style_bg, lv_color_hex(0xFFFFFF));  // 白色背景
    lv_obj_add_style(lv_scr_act(), &style_bg, 0);

    // 创建地面
    if (ground) lv_obj_del(ground);
    ground = lv_obj_create(lv_scr_act());
    lv_obj_set_size(ground, SCREEN_WIDTH, GROUND_HEIGHT);
    lv_obj_set_pos(ground, 0, GROUND_Y);
    lv_obj_set_style_bg_color(ground, lv_color_hex(0xb8842d), 0); 


    // 创建小鸟
    if (bird) lv_obj_del(bird);
    bird = lv_obj_create(lv_scr_act());
    lv_obj_set_size(bird, BIRD_SIZE, BIRD_SIZE);
    lv_obj_set_pos(bird, 50, bird_y); 
    lv_obj_set_style_bg_color(bird, lv_palette_main(LV_PALETTE_YELLOW), 0);
    lv_obj_set_style_radius(bird, 5, 0);


    // 初始化管道（确保均匀分布）
    int current_x = SCREEN_WIDTH-150;  // 从屏幕右侧开始
    for (int i = 0; i < 10; i++) {
        // 初始管道间距
        int random_gap = MIN_PIPE_SPACING + (rand() % (MAX_PIPE_SPACING - MIN_PIPE_SPACING + 1));
        pipe_x[i] = current_x + random_gap;
        current_x = pipe_x[i];  // 更新当前X为下一个管道的基准
        
        int max_top = SCREEN_HEIGHT - PIPE_GAP - GROUND_HEIGHT - 50;
        if (max_top < 30) max_top = 30;
        pipe_top_height[i] = 30 + (rand() % (max_top - 30));

        // 创建上管
        if (pipes[i]) lv_obj_del(pipes[i]);
        pipes[i] = lv_obj_create(lv_scr_act());
        lv_obj_set_size(pipes[i], PIPE_WIDTH, pipe_top_height[i]);
        lv_obj_set_pos(pipes[i], pipe_x[i], 0);
        lv_obj_set_style_bg_color(pipes[i], lv_palette_main(LV_PALETTE_GREEN), 0);

        // 创建下管
        if (bottom_pipes[i]) lv_obj_del(bottom_pipes[i]);
        int bottom_pipe_y = pipe_top_height[i] + PIPE_GAP;
        int bottom_pipe_h = GROUND_Y - bottom_pipe_y;
        if (bottom_pipe_h < 30) bottom_pipe_h = 30;
        bottom_pipes[i] = lv_obj_create(lv_scr_act());
        lv_obj_set_size(bottom_pipes[i], PIPE_WIDTH, bottom_pipe_h);
        lv_obj_set_pos(bottom_pipes[i], pipe_x[i], bottom_pipe_y);
        lv_obj_set_style_bg_color(bottom_pipes[i], lv_palette_main(LV_PALETTE_GREEN), 0);
    }
 

    // 分数标签
    if (!score_label) {
        score_label = lv_label_create(objects.app3_gmae);  // 绑定到游戏页面
        int label_width = lv_obj_get_width(score_label);
        int center_x = (SCREEN_WIDTH - label_width) / 2;
        lv_obj_set_pos(score_label, center_x, 10);
        lv_obj_set_style_text_color(score_label, lv_color_black(), 0);
        lv_obj_set_style_text_font(score_label, &font_puhui_20_4, 0);
    }
    lv_label_set_text(score_label, "0");  // 此时score_label已确保有效
    lv_obj_move_foreground(score_label);

    // 注册触摸事件
    lv_obj_remove_event_cb(lv_scr_act(), touch_event_handler);
    lv_obj_add_event_cb(lv_scr_act(), touch_event_handler, LV_EVENT_PRESSED, NULL);


    // 创建游戏定时器
    if (game_timer) lv_timer_del(game_timer);
    game_timer = lv_timer_create(game_timer_cb, 20, NULL);

}

// 开始游戏
void action_start_game(lv_event_t *e) {

    reset_game();
    ESP_LOGI(TAG, "重置游戏");
            // 移除游戏结束得分标签
    if (game_over_score_label) {
        lv_obj_del(game_over_score_label);
        game_over_score_label = nullptr;
    }
    
    init_game_scene();
    ESP_LOGI(TAG, "初始化屏幕");
    game_started = true;
    if (objects.ball_start) {
        lv_obj_add_flag(objects.ball_start, LV_OBJ_FLAG_HIDDEN);
    }
}

// 打开游戏界面
void action_lcon_game(lv_event_t *e) {
    ESP_LOGI(TAG, "打开Flappy Bird游戏");

        // create_screen_app3_gmae();
        lv_scr_load(objects.app3_gmae);


}


void action_exit_game(lv_event_t * e)
{
    ESP_LOGI(TAG, "退出游戏");
    lv_indev_t * indev = lv_indev_get_act();
    lv_point_t vect;

    if(indev) {
        lv_indev_get_vect(indev, &vect);
        if(vect.x > -20) {  
        lv_scr_load(objects.app3_page);
        }
    }
}